// GetPropertyFunctionTrigger.cpp: implementation of the GetPropertyFunctionTrigger class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "phsshare.h"
#include "GetPropertyFunctionTrigger.h"
#include "GetPropertyFunction.h"
#include "GetPropertyRegularInfo.h"
#include "Part.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

GetPropertyFunctionTrigger::GetPropertyFunctionTrigger()
{
	m_pPart = NULL;
	m_nState = TRUE;
}

GetPropertyFunctionTrigger::~GetPropertyFunctionTrigger()
{

}

void GetPropertyFunctionTrigger::Trigger()
{
	ASSERT(m_pPart);
	if(m_nState)
	{
		GetTriggerFuns();
		RunFuns();
	}
}

void GetPropertyFunctionTrigger::Add(GetPropertyFunction* pFunction)
{
	ASSERT(pFunction);
	GetPropertyFunction* pTemp = NULL;
	GetPropertyFunction* pInsert = pFunction;

	POSITION pos = m_theTriggerFuns.GetHeadPosition();
	POSITION Oldpos = pos;
	while(pos)
	{
		Oldpos = pos;
		pTemp = m_theTriggerFuns.GetNext(pos);
		ASSERT(pTemp);

		INT nTemp = pTemp->Prior()>>16;
		INT nFun = pFunction->Prior()>>16;

		INT nTempOrder = 0x0000FFFF&(pTemp->Prior());
		INT nFunOrder = 0x0000FFFF&(pFunction->Prior());
		
		if(nTemp < nFun)
		{
			m_theTriggerFuns.RemoveAll();
			m_theTriggerFuns.AddHead(pFunction);
			return;
		}
		else if(nTemp == nFun)
		{
			if(nTempOrder < nFunOrder)
			{
				continue;
			}
			else
			{
				m_theTriggerFuns.InsertBefore(Oldpos, pFunction);
				return;
			}
		}
		else
		{
			return;
		}
	}
	m_theTriggerFuns.AddTail(pInsert);
}

void GetPropertyFunctionTrigger::GetTriggerFuns()
{
	GetPropertyRegularInfo info(m_pPart);

	GetPropertyFunction* pFun = info.GetFirst();
	while(pFun != NULL)
	{
		if(pFun->IsFill())
		{
			Add(pFun);
		}
		pFun = info.GetNext();
	}
}

void GetPropertyFunctionTrigger::RunFuns()
{
	Close();

	POSITION pos = m_theTriggerFuns.GetHeadPosition();

	GetPropertyFunction* pFun = NULL;
	GetPropertyFunction* pOld = NULL;
	while(pos)
	{
		pOld = pFun;
		pFun = m_theTriggerFuns.GetNext(pos);
		ASSERT(pFun);
		BOOL bResult = pFun->GetProperties();
		if(bResult)
		{
			pFun->ResetCondition();
		}
		ASSERT(pOld == NULL || pOld->Prior() <= pFun->Prior());
	}

	m_theTriggerFuns.RemoveAll();
	Open();
}
